package com.amigo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.anim;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.amigo.helper.Constants;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;

public class MainActivity extends Activity {
	
	private String TokenfromDB ; 
	private TextView status ; 
	private String url = Constants.base_url + "checkLoggedUser" ;
	
	private String DB_USER;
	boolean Success;
	private String Message ;
	private LinearLayout tryagain;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		
		status = (TextView) findViewById(R.id.InternetStatus);
		TokenfromDB = JsonFileUtility.ReadJsonData(Constants.TAG_UserGUID);
		tryagain = (LinearLayout) findViewById(R.id.tryagain);
		tryagain.setVisibility(View.GONE);
		tryagain.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				new CheckInternetTask().execute();
				
			}
		});
		
	
		
		new CheckInternetTask().execute();
		
		
		
	}
public class CheckInternetTask extends AsyncTask<Void, Void, Void>
{boolean check ;

	@Override
	protected Void doInBackground(Void... params) {
		check = internetconnected();
		return null;
	}
	@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (check)
			{
				if (!TokenfromDB.equals("init"))
				{
					Log.d("Tag" , "in-if");
					new CheckUsertokenTask().execute();
				}
				else{
					Log.d("Tag" , "in-else");
					startActivity(new Intent(MainActivity.this , Login.class));
				}
				
			}
			else
			{
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("No Internet Connection Found");
				builder.setMessage("Please try again once you're connected to Internet.");
				builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						status.setText("No Internet Connection Found");
						tryagain.setVisibility(View.VISIBLE);
					}
				});

				AlertDialog alertDialog = builder.create();
				alertDialog.setCancelable(false);
				
				// show it
				alertDialog.show();
			}
			
		
		}
	}
	private boolean internetconnected() {
	
		    boolean haveConnectedWifi = false;
		    boolean haveConnectedMobile = false;

		    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		    for (NetworkInfo ni : netInfo) {
		        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
		            if (ni.isConnected())
		                haveConnectedWifi = true;
		        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
		            if (ni.isConnected())
		                haveConnectedMobile = true;
		    }
		    return haveConnectedWifi || haveConnectedMobile;
		}
		
	
	public class CheckUsertokenTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params_check = new ArrayList<NameValuePair>();
			params_check.add(new BasicNameValuePair("token", TokenfromDB));
			
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,
					params_check);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {

					JSONObject jsonObj = new JSONObject(jsonStr);

					Success = jsonObj.getBoolean("success");
					Message = jsonObj.getString("message");
					
					

					if (Success == true) {
						JSONObject user = jsonObj.getJSONObject("user");
						DB_USER = user.toString();

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}
	@Override
	protected void onPostExecute(Void result) {
		
		super.onPostExecute(result);
		if (Success == false)
		{
			status.setText(Message);
			tryagain.setVisibility(View.VISIBLE);
			startActivity(new Intent(MainActivity.this , Login.class));
			
		}
		if (Success == true) {

			
			JsonFileUtility.CreateAndSaveFile(Constants.TAG_UserObject,
					DB_USER);
			Intent i = new Intent(MainActivity.this, Dashboard.class);
			overridePendingTransition(anim.fade_in, anim.fade_out);
			startActivity(i);

		}
	}	
	}
	

}
